package cn.da.shuai.cool.system.service.service.impl;

import cn.da.shuai.cool.mybatis.service.impl.CoolServiceImpl;
import cn.da.shuai.cool.redis.service.RedisService;
import cn.da.shuai.cool.system.service.mapper.CoolConfigMapper;
import cn.da.shuai.cool.system.model.entity.config.CoolConfig;
import cn.da.shuai.cool.system.service.service.ICoolConfigService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * 参数配置服务实现类
 */
@Service
public class CoolConfigServiceImpl extends CoolServiceImpl<CoolConfigMapper, CoolConfig> implements ICoolConfigService {

    @Autowired
    private RedisService redisService;

    /**
     * 参数配置缓存前缀
     */
    private static final String CACHE_PREFIX = "sys_config:";

    @Override
    public String selectConfigByKey(String configKey) {
        String configValue = (String) redisService.get(getCacheKey(configKey));
        if (StrUtil.isNotEmpty(configValue)) {
            return configValue;
        }
        CoolConfig config = this.getOne(new LambdaQueryWrapper<CoolConfig>().eq(CoolConfig::getConfigKey, configKey));
        if (Objects.nonNull(config)) {
            redisService.set(getCacheKey(configKey), config.getConfigValue());
            return config.getConfigValue();
        }
        return StrUtil.EMPTY;
    }

    @Override
    public CoolConfig selectConfigById(Long configId) {
        return this.getById(configId);
    }


    @Override
    public void loadingConfigCache() {
        List<CoolConfig> configsList = this.list();
        for (CoolConfig config : configsList) {
            redisService.set(getCacheKey(config.getConfigKey()), config.getConfigValue());
        }
    }

    @Override
    public void clearConfigCache() {
        redisService.delete(CACHE_PREFIX + "*");
    }

    @Override
    public void resetConfigCache() {
        clearConfigCache();
        loadingConfigCache();
    }

    @Override
    public boolean checkConfigKeyUnique(CoolConfig config) {
        long configId = Objects.isNull(config.getId()) ? -1L : config.getId();
        CoolConfig info = this.getOne(new LambdaQueryWrapper<CoolConfig>()
                .eq(CoolConfig::getConfigKey, config.getConfigKey())
                .last("limit 1"));
        return info != null && info.getId() != configId;
    }

    /**
     * 设置cache key
     *
     * @param configKey 参数键
     * @return 缓存键key
     */
    private String getCacheKey(String configKey) {
        return CACHE_PREFIX + configKey;
    }
}